/**************************************************************************
 * @doc Comm
 * @module syncdial.C 
 * Synchronous dialing task
 *
 * Product     :   
 * <nl>Developer   :   
 * <nl>Notes       :
 *
 * @head3 Comm Functions |
 * @index | Comm
 * @end
 *
 * Copyright (c) 1996-2000 by VeriFone Inc. All rights reserved.
 * 
 * No part of this software may be used, stored, compiled, reproduced,
 * modified, transcribed, translated, transmitted, or transferred, in any form 
 * or by any means whether electronic, mechanical, magnetic, optical, 
 * or otherwise, without the express prior written permission of VeriFone, Inc.
 *
 * Revision History
 * Date						Author								Purpose			
 * 31-Aug-2005			CHIA Lee Chyi				To resolve the Vx510 Combo Modem problem
 * ------------------------------------------------------------------------
$Log:
 * ------------------------------------------------------------------------
 ********************************************************************************/

#include <project.h>

#include <xmodem.h>
#include <ascii.h>
#include <acldev.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ACLStr.h>
#include <txoinc.h>
#include <svc.h>
#include <ctype.h>
#include <aclconio.h>
#define DEBUG_SYNCDIAL
#ifdef DEBUG_SYNCDIAL
#define DEBUG_95
#endif

#include <mdmdefs.h>
#include <syncdial.h>
#include <spdebug.h>
#include <modem.h>
#include <comm.h>

VS_BOOL fMDMInitDone = VS_FALSE;

int my_xmdm_inInitModem(int h_modem,int i_max_wait,int a,int b,int c,int d,int e);
int Lenz_xhayes_send_cmd(int h_modem,const char* cmd_buff);
int inDial(int* h_modem,SYNC_DIAL_OBJECT* pobSyncTask) {
    int DialResult = VS_ERR;
    int Baud = pobSyncTask->shBaudRate;
    int DataFormat = (pobSyncTask->fAsync ? pobSyncTask->shDataFormat : Fmt_A7E1);
    char Phone[40];//kv1 debug - should be max phone + PABX
    VS_BOOL fSync = !(pobSyncTask->fAsync);

	int inModemType;

	char gpsbuf[5];	// Alona_G1 03March2006 -- put fix on related bug cause by 6A3 OS by India team

	// Vinaya HS - ASPEN/TDK Modem on 3750 will not work if Baud variable is hard-coded to 9 (or 115200) where as Connexant Modem 
	//			  on Predator will work only when the Baud variable is hard-coded to 9.

	inModemType = SVC_INFO_MOD_ID();
	
	//LeeChyi - 31082005: To resolve the Vx510 Combo Modem problem - START
	/*
	if(inModemType == CONNEXANT_MODEM_ID)
	{
		LOG_PRINTFF((0x8L, "Setting baud rate to 115200"));
		Baud = Rt_115200;
	}*/
	
	switch ( inModemType)
		{
		case 2:
		case 3:	break;
		default : 
			Baud = Rt_115200;
	}
	//LeeChyi - END

    if ((DialResult = inSPOpenModem(h_modem, Baud, DataFormat)) == SUCCESS) {
        if ((DialResult = inCheckline(*h_modem)) == SUCCESS) {
            //do {
            if ((DialResult = my_xmdm_inInitModem(*h_modem, 3, 1, 2, 3, 4, 5)) != HAYES_OK)
                //  DialResult=inSPInitModem(*h_modem, fSync);
                LOG_PRINTFF((0x08L, "Init Status  %d   ", DialResult));
            // } while(DialResult==999);
            if (DialResult == HAYES_OK) {
                int w,
                length;

                MEMCLR(Phone, sizeof(Phone));
                vdFormatPhoneNumber(pobSyncTask->szPABXCode, 
                pobSyncTask->szPhoneNumber, 
                pobSyncTask->fDialType, 
#ifdef DTR_DIAL                                        
                fSync,
#endif                                        
                Phone);
                length = strlen(Phone);
                LOG_PRINTFF((0x08L, "Dial %s    ", Phone));
                //pdebug (("Dial,pre (%d)-%s",length,Phone));
                w = write(*h_modem, Phone, length);
				
		//START: Alona_G1 03March2006 -- put fix on related bug cause by 6A3 OS by India team
				memset(gpsbuf, 0x00, sizeof(gpsbuf));
				while	(get_port_status(*h_modem, gpsbuf) !=0);		//wait for the ATDT command to exit COM3
		// END
                LOG_PRINTFF((0x08L, "Dial %s     %d", Phone, w));

                pdebug(("Dial,pre (%d)-%s Actual Written %d", length, Phone, w));
                //pdebug (("write=%d",w));
                //pdebug (("Dial,post (%d)-%s",length,Phone));
                if (w != length) {
                    DialResult = w;
                    //                    pdebug (("Modem Write Error=%d, errno=%d",DialResult,errno));
                }
            } else
                pdebug(("Modem Init Error=%d", DialResult));
        } else
            pdebug(("Checkline Error=%d", DialResult));
    } else {
        //  pdebug (("Modem Open Error=%d, errno=%d",DialResult,errno));
    }

    return (DialResult);
}

int inConnect(int* h_modem,int h_pipe,int Baud,VS_BOOL fSync) {
    int ConnectResult;
    int pipe_data_ln = 0;
    SYNC_DIAL_OBJECT obTaskData;



    do {
        ConnectResult = inGetMdmResponse(*h_modem, 3);

        // Check for pipe message
        pipe_data_ln = read(h_pipe, (char *) &obTaskData, sizeof(SYNC_DIAL_OBJECT));


        //pdebug (("ConnectResult=%d",ConnectResult));
    } while (ConnectResult == E_X_HR_TIMEOUT && pipe_data_ln == 0);

    if (pipe_data_ln > 0) {
        if (obTaskData.fAbort) {
            //pdebug (("ABORT"));
        } else
            pdebug(("BAD PIPE MSG"));
        ConnectResult = MDM_DEV_ABORT;
    } else if (pipe_data_ln < 0) {
        //pdebug (("pipe_data_ln=%d,errno=%d",pipe_data_ln,errno));
        ConnectResult = VS_ERR;
    } else {
        // Check the result code
        switch (ConnectResult) {
#ifdef SYNC_CTS_CHECK
        case VFI_SYNC_CONNECT:
#endif                          
        case CONNECT:
            // Generic CONNECT or CONNECT_300
        case CONNECT_1200:
        case CONNECT_2400:
        case CONNECT_4800:
        case CONNECT_9600:
            if (fSync) {
                struct  Opn_Blk ob;
                //Switch to SDLC and make sure DTR and RTS are asserted.
                Baud = 9;
                ob.rate = Baud;
                ob.format = Fmt_SDLC | Fmt_DTR | Fmt_RTS  ;
                ob.protocol = P_sdlc_mode;                                       
                ob.trailer.sdlc_parms.address = 0x30;
                ob.trailer.sdlc_parms.option = P_sdlc_sec; 
                MDM_WRITE_BLK(*h_modem, ob);
                // testing indicated, this is required for some host
                //SVC_WAIT(4 * 1000);   
            }
            break;

        default:
            break;
        }// end 'Check the result code' switch
    }

    return ConnectResult;
}

int inSPOpenModem(int* h_modem,int Baud,int Format) {
    int retVal;
    int inModemType;		//LeeChyi - 31082005: To fix the Vx510 Combo Modem problem
    

    *h_modem = VS_ERR;
    retVal = open(MDM_PORT, 0); 

    if (retVal > 0) {
        *h_modem = retVal;
        
     	//LeeChyi - 31082005: To fix the Vx510 Combo Modem problem - START
   		inModemType = SVC_INFO_MOD_ID();
		switch ( inModemType) {
			case 2:
			case 3:
			case 4:
				//set_combo_mode(0);	// 04Jan2005 commented for dialup terminal 
				break;
				
			default :
				//set_combo_mode(0); //04Jan2005 commented for dialup terminal
				break;
		}
		//LeeChyi - END
	
        if ((retVal = xmdm_set_protocol(*h_modem, Baud, Format)) != VS_SUCCESS) {
            close(*h_modem);
            *h_modem = VS_ERR;
        }
    }

    return (retVal);
}

int inSPInitModem(int h_modem,VS_BOOL fSync) {
    int retVal;
    int length;
    char MdmEnvBuf[75];

    // Process SP*MI1

    MEMCLR(MdmEnvBuf, sizeof(MdmEnvBuf));
    if (get_env("*VINIT0", MdmEnvBuf, sizeof(MdmEnvBuf)) > 0) {
        //pdebug (("%s=%s",SOFTPAY_BASE_MDM_ENV_VAR1,MdmEnvBuf));
        length = strlen(MdmEnvBuf);
        //retVal = inSendMdmCmd (h_modem, MdmEnvBuf); ATL 2002/01/31
        retVal = xhayes_send_cmd(h_modem, MdmEnvBuf);
        //pdebug (("inSendMdmCmd,retVal=%d",retVal));
        if (retVal == (length + 3)) {
            if ((retVal = inGetMdmResponse(h_modem, 2)) != HAYES_OK)
                pdebug(("inGetMdmResponse,retVal=%d", retVal));
            SVC_WAIT(MDM_CMD_WAIT_TIME); // Give Modem time to process command
        } else {
            if (retVal < 0) {
                //   pdebug (("errno=%d",errno));
            }
            retVal = E_WRITE;
        }
    }

    if (get_env("*VINIT1", MdmEnvBuf, sizeof(MdmEnvBuf)) > 0) {
        //pdebug (("%s=%s",SOFTPAY_BASE_MDM_ENV_VAR1,MdmEnvBuf));
        length = strlen(MdmEnvBuf);
        //retVal = inSendMdmCmd (h_modem, MdmEnvBuf); ATL 2002/01/31
        retVal = xhayes_send_cmd(h_modem, MdmEnvBuf);
        //pdebug (("inSendMdmCmd,retVal=%d",retVal));
        if (retVal == (length + 3)) {
            if ((retVal = inGetMdmResponse(h_modem, 2)) != HAYES_OK)
                pdebug(("inGetMdmResponse,retVal=%d", retVal));
            SVC_WAIT(MDM_CMD_WAIT_TIME); // Give Modem time to process command
        } else {
            if (retVal < 0) {
                //   pdebug (("errno=%d",errno));
            }
            retVal = E_WRITE;
        }
    }

    if (retVal == HAYES_OK) {
        // Process SP*MI2
        MEMCLR(MdmEnvBuf, sizeof(MdmEnvBuf));
        if (get_env("*VINIT2", MdmEnvBuf, sizeof(MdmEnvBuf)) > 0) {
            //pdebug (("%s=%s",SOFTPAY_BASE_MDM_ENV_VAR2,MdmEnvBuf));
            length = strlen(MdmEnvBuf);
            //retVal = inSendMdmCmd (h_modem, MdmEnvBuf); ATL 2002/01/31
            retVal = xhayes_send_cmd(h_modem, MdmEnvBuf);
            //pdebug (("inSendMdmCmd,retVal=%d",retVal));
            if (retVal == (length + 3)) {
                if ((retVal = inGetMdmResponse(h_modem, 2)) != HAYES_OK)
                    pdebug(("inGetMdmResponse,retVal=%d", retVal));
                SVC_WAIT(MDM_CMD_WAIT_TIME); // Give Modem time to process command
            } else {
                if (retVal < 0) {
                    //pdebug (("errno=%d",errno));
                }
                retVal = E_WRITE;
            }
        }
    }

    if (fSync && retVal == HAYES_OK) {
        // Process #SI
        MEMCLR(MdmEnvBuf, sizeof(MdmEnvBuf));
        if (get_env("*VINIT3", MdmEnvBuf, sizeof(MdmEnvBuf)) > 0) {
            //pdebug (("%s=%s",SYNC_MODEM_ENVIRONMENT_VARIABLE,MdmEnvBuf));
            length = strlen(MdmEnvBuf);
            //retVal = inSendMdmCmd (h_modem, MdmEnvBuf); ATL 2002/01/31
            retVal = xhayes_send_cmd(h_modem, MdmEnvBuf);
            //pdebug (("inSendMdmCmd,retVal=%d",retVal));
            if (retVal == (length + 3)) {
                if ((retVal = inGetMdmResponse(h_modem, 2)) != HAYES_OK)
                    pdebug(("inGetMdmResponse,retVal=%d", retVal));
                SVC_WAIT(MDM_CMD_WAIT_TIME); // Give Modem time to process command
            } else {
                if (retVal < 0) {
                    //     pdebug (("errno=%d",errno));
                }
                retVal = E_WRITE;
            }
        }
    }

    if (!fSync && retVal == HAYES_OK) {
        // Process #AI
        MEMCLR(MdmEnvBuf, sizeof(MdmEnvBuf));
        if (get_env(ASYNC_MODEM_ENVIRONMENT_VARIABLE, MdmEnvBuf, sizeof(MdmEnvBuf)) > 0) {
            //pdebug (("%s=%s",ASYNC_MODEM_ENVIRONMENT_VARIABLE,MdmEnvBuf));
            length = strlen(MdmEnvBuf);
            //retVal = inSendMdmCmd (h_modem, MdmEnvBuf); ATL 2002/01/31
            retVal = xhayes_send_cmd(h_modem, MdmEnvBuf);
            //pdebug (("inSendMdmCmd,retVal=%d",retVal));
            if (retVal == (length + 3)) {
                if ((retVal = inGetMdmResponse(h_modem, 2)) != HAYES_OK)
                    pdebug(("inGetMdmResponse,retVal=%d", retVal));
                SVC_WAIT(MDM_CMD_WAIT_TIME); // Give Modem time to process command
            } else {
                if (retVal < 0) {
                    //   pdebug (("errno=%d",errno));
                }
                retVal = E_WRITE;
            }
        }
    }

    if (retVal == HAYES_OK) {
        // Process *MI
        MEMCLR(MdmEnvBuf, sizeof(MdmEnvBuf));
        if (get_env(MODEM_ENVIRONMENT_VARIABLE, MdmEnvBuf, sizeof(MdmEnvBuf)) > 0) {
            //pdebug (("%s=%s",MODEM_ENVIRONMENT_VARIABLE,MdmEnvBuf));
            length = strlen(MdmEnvBuf);
            //retVal = inSendMdmCmd (h_modem, MdmEnvBuf); ATL 2002/01/31
            retVal = xhayes_send_cmd(h_modem, MdmEnvBuf);
            //pdebug (("inSendMdmCmd,retVal=%d",retVal));
            if (retVal == (length + 3)) {
                if ((retVal = inGetMdmResponse(h_modem, 2)) != HAYES_OK)
                    pdebug(("inGetMdmResponse,retVal=%d", retVal));
                SVC_WAIT(MDM_CMD_WAIT_TIME); // Give Modem time to process command
            } else {
                if (retVal < 0) {
                    //  pdebug (("errno=%d",errno));
                }
                retVal = E_WRITE;
            }
        }
    }

    return (retVal);
}



#ifdef DTR_DIAL
void vdFormatPhoneNumber(char* PABX,char* PhoneNum,VS_BOOL fDialType,VS_BOOL fSync,char* Fmt_Phone)
#else
void vdFormatPhoneNumber(char* PABX,char* PhoneNum,VS_BOOL fDialType,char* Fmt_Phone)
#endif
{
    char zphone[40];

    //pdebug (("vdFormatSyncPhoneNumber"));
    //pdebug (("PABX=%s",PABX));
    //pdebug (("PhoneNum=%s",PhoneNum));
    //pdebug (("fDialType=%d",fDialType));

    MEMCLR(zphone, sizeof(zphone));

#ifdef DTR_DIAL 
    if (fSync && (is37xx() == FALSE))
        strcat(zphone, "AT&Z0=");
    else
    #endif
        strcat(zphone, "ATD");

    if (fDialType)
        strcat(zphone, "P");
    else
        strcat(zphone, "T");

    if (strlen(PABX) > 0)
        strcat(zphone, PABX);

    strcat(zphone, PhoneNum);
    strcat(zphone, "\r");

    strcpy(Fmt_Phone, zphone);
    //pdebug (("Fmt_Phone=%s",Fmt_Phone));
}

int inOldCheckline(int h_modem);
int inOldCheckline(int h_modem) {
    int Loop = 0;
    int retVal = SUCCESS;

    if (is37xx() == TRUE)
        do {
            // Send the AT- command to get the line status for the TDK modem
            if ((retVal = inSendMdmCmd(h_modem, "-")) == 4) {
                retVal = inGetMdmResponse(h_modem, 2);
                SVC_WAIT(55); // Give Modem time for extra junk response
                // xmdm_flush(h_modem); // flush out any pending response
                inGetMdmResponse(h_modem, 2);            
                //pdebug (("retVal=%d",retVal));

                if (retVal >= 100) {
                    pdebug(("B"));
                    //  Modem returns even no for no_line. 
                    if ((retVal % 2) == 0)
                        retVal = VFI_NO_LINE;
                    else
                        retVal = SUCCESS;
                } else {
                    SVC_WAIT(1000);
                    retVal = E_X_HR_TIMEOUT; // SENDING 
                }
            }
        } while (retVal == E_X_HR_TIMEOUT && ++Loop < 3);

    return (retVal);
}               

void Hangup(int h_modem) {
    //pdebug (("--Hangup--"));

    SetSerialLines(h_modem, DTR_OFF);
    SVC_WAIT (2000);
    SetSerialLines(h_modem, DTR_ON);
    xhayes_response(h_modem, -1, 1);
}

/********************************************************************************************* 
* @func int | inCloseModem | 
*       Closes the modem for use 
*
* @parm int | h_modem |                     Modem file handle
*       int | inDataFormat |                Port data format
*       int | inBaudRate |                  Port baud rate
*
* @rdesc return values.
* @flag int |  value from the xmdm_close call
* @end
**********************************************************************************************/

int inCloseModem(int h_modem) {
    int inCloseResult = 0;

    // pdebug(("--inCloseModem--[h_modem=%d]",h_modem));

    //inCloseResult = my_xmdm_hangup(h_modem,0,0);
    //pdebug (("xmdm_hangup=%d",inCloseResult));

    //kv1 debug - do not hang up to quick

	if ( xmdm_check_status( h_modem, MDM_DCD ) == 0 )
		SVC_WAIT (1000);

    Hangup(h_modem);

    //  inCloseResult = xmdm_close(h_modem, 0, 0);
    //pdebug (("xmdm_close=%d",inCloseResult));

    //if (inCloseResult < 0)
    //{
    inCloseResult = close(h_modem); 
    // } 

    return(VS_SUCCESS);
}

int inOldGetMdmResponse(int h_modem,int TimeOut);
int inOldGetMdmResponse(int h_modem,int TimeOut) {
    int index;
    int bytes;
    int modem_resp = -1;
    long Ticks;
    char MdmResponseBuf[60];         // kv1 debug, should be max modem command in case of echo
    VS_BOOL fInvalid;

    //pdebug (("--inGetMdmResponse--"));

    Ticks = set_itimeout(NO_CLOCK_HANDLE TimeOut, TM_SECONDS); // TM_SECONDS = 1000
    while (TRUE) {
        fInvalid = FALSE;
        index = 0;
        MEMCLR(MdmResponseBuf, sizeof(MdmResponseBuf));
        do {
            bytes = read(h_modem, &MdmResponseBuf[index], 1); // get result code
            if (bytes == 1) {
                pdebug(("MdmRep =%02X,index=%d Ticks =%d   Timeout = %d", MdmResponseBuf[index], index, Ticks, TimeOut));
                if (MdmResponseBuf[index] != '\r' && !isdigit(MdmResponseBuf[index]) && !fInvalid) {
                    fInvalid = TRUE;
                    pdebug(("Invalid=%02X,index=%d", MdmResponseBuf[index], index));
                }
                index++;
            }
        } while ((MdmResponseBuf[index - 1] != '\r') && (CHECK_TIMEOUT(Ticks)) && bytes >= 0 && index < sizeof(MdmResponseBuf));

        pdebug(("Resp %s", MdmResponseBuf));
        if (bytes < 0) {
            //pdebug (("bytes=%d,errno=%d",bytes,errno));
            break;
        }

        if (index >= sizeof(MdmResponseBuf)) {
            pdebug(("inGetMdmResponse-OVERRUN"));
            break;
        }

        /*        if (CHECK_TIMEOUT(Ticks) == 0)
            {
               //pdebug (("CHECK_TIMEOUT(Ticks)"));
            modem_resp = E_X_HR_TIMEOUT;
                break;
            } */

        if (MdmResponseBuf[index - 1] == '\r') {
            // Maximum response in numeric mode is 3 chars 'nnn\r'
            if (!fInvalid) {
                modem_resp = atoi(MdmResponseBuf);
                //pdebug (("modem_resp=%d",modem_resp));
                break;
            }
            // Assume command echo, ignore and look for response
            else {
                //pdebug (("Modem command echo!"));
            }
        }
        if (CHECK_TIMEOUT(Ticks) == 0) {
            pdebug(("CHECK_TIMEOUT(Ticks)"));
            modem_resp = E_X_HR_TIMEOUT;
            break;
        }
    };

    return (modem_resp);
}

void SetSerialLines(int h_modem,char ucData) {
    char data_buf[2];

    //pdebug (("SSL - [%02X]",ucData));
    MEMCLR(data_buf, 2);
    data_buf[0] = ucData;
    set_serial_lines(h_modem, data_buf);
    //pdebug (("SSL Result = %d", bytes));
}

int inSendMdmCmd(int h_modem,char* cmd_buff) {
    int k,
    y;
    int xx;      /* Return value */
    char buffer[100];
    char command[89];

    memset(buffer, '\0', sizeof(buffer));
    memset(command, '\0', sizeof(command));

    /* Shift the command buffer to the right by 2 chars,
       * if 'cmd_buf' is 0 length then no shift is done.
       */
    y = strlen(cmd_buff);

    for (k = y + 1; k >= 2; --k) {
        command[k] = cmd_buff[k - 2];
    }

    /* Put in the hayes "AT" command prefix, <CR> suffix and null terminate.
     */
    command[0] = 'A' ;
    command[1] = 'T' ;
    command[y + 2] = '\r';
    command[y + 3] = 0;
    pdebug(("CMD %s", command))
    xx = write(h_modem, command, y + 3);

    return (xx);
}

int inGetModem(int h_modem,int inLocalTaskId) {
    int inRetVal = VS_ERR;
    int inLoop = 0;
    int inOwnerTaskId;
    char szDevName[DEVICE_NAME_SIZE];

    //pdebug (("--inGetModem--"));
    //pdebug (("inLocalTaskId=%d",inLocalTaskId));

    MEMCLR(szDevName, DEVICE_NAME_SIZE);
    strcpy(szDevName, MDM_PORT);
    do {
        h_modem = get_owner(szDevName, &inOwnerTaskId);
        if (inLocalTaskId == inOwnerTaskId) {
            inRetVal = VS_SUCCESS;
            break;
        }
        //SVC_WAIT(20);
        SVC_WAIT(5);
        ++inLoop;
    } while (inLoop <= 75);  //kv1 debug - arbitrary loop setting

    //pdebug (("inRetVal=%d",inRetVal));
    return (inRetVal);
}

int my_xmdm_checkline(int h_modem);

int inCheckline(int h_modem) {
    int ChecklineResult = SUCCESS;

    if (is37xx() == TRUE)
        ChecklineResult = my_xmdm_checkline(h_modem);

    return (ChecklineResult);
}


//int xmdm_checkline(int h_modem)
int my_xmdm_checkline(int h_modem) {
    int Loop = 0;
    int retVal = SUCCESS;
    int retStatus = 1;

    if (is37xx() == TRUE)
        do {
            // Send the AT- command to get the line status for the TDK modem
            if ((retVal = xhayes_send_cmd(h_modem, "-")) == 4) {
                SVC_WAIT(55);          

                retVal = xhayes_response(h_modem, -1, 2);
                //LOG_PRINTF(("xmdm_checkline Response %d", retVal));

                if (retVal < 0) {
                    LOG_PRINTF(("xmdm_checkline Response %d", retVal));
                    return retVal;
                }

                if (retVal > 100) {
                    //  Modem returns even no for no_line. 
                    if ((retVal % 2) == 0)
                        retVal = VFI_NO_LINE;
                    else
                        retVal = SUCCESS;
                } else {
                    LOG_PRINTF(("xmdm_checkline Response %d", retVal));
                    retVal = SUCCESS ;   //Any response between 0 and 99 
                    //ERR_BEEP();
                    //SVC_WAIT(300);
                    //ERR_BEEP();
                    //SVC_WAIT(300);
                    //ERR_BEEP();  
                }

                //  xmdm_flush(h_modem); // flush out any pending response

                while ((retStatus = xmdm_output_pending(h_modem)) == 1) ;
                if (retStatus == SUCCESS)
                    xmdm_flush(h_modem);
                else {
                    LOG_PRINTF(("xmdm_output_pending Response %d", retStatus));   
                    retVal = E_OUTPUT_FAILED;
                }
            }
        } while (retVal == E_X_HR_TIMEOUT && ++Loop < 3);
    else
        // line status is supported only for the TDK modem so far
        return E_X_FEATURE_NOT_SUPPORTED ;

    return (retVal);
}               


//int xhayes_response( int h_modem, int h_clock, int i_max_wait )
int inGetMdmResponse(int h_modem,int i_max_wait) {
    int h_clock = -1;

    int index = 0;
    int bytes;
    int alphaFlag ;
    int modem_resp = -1;
    long l_max_ticks = 0;
    char MdmResponseBuf[100] = {
        0
    };         


    if (i_max_wait > 0)
        l_max_ticks = set_itimeout(h_clock, i_max_wait, TM_SECONDS);
    else if (i_max_wait == -1)
        l_max_ticks = set_itimeout(h_clock, (TICKS_PER_SEC / 5), TM_TICKS);


    while (TRUE) {
        alphaFlag = FALSE;
        index = 0;
        memset(MdmResponseBuf, '\0', sizeof(MdmResponseBuf));
        do {
            bytes = read(h_modem, &MdmResponseBuf[index], 1); // get result code
            if (bytes == 1) {
                if (MdmResponseBuf[index] != '\r' && !isdigit(MdmResponseBuf[index]) && !alphaFlag)
                    alphaFlag = TRUE;
                index++;
            }
        } while ((MdmResponseBuf[index - 1] != '\r') && (SVC_TICKS(0, (long *) &l_max_ticks)) && bytes >= 0 && index < sizeof(MdmResponseBuf));

        if (bytes < 0)
            break;

        if (index >= sizeof(MdmResponseBuf))
            break;

        if (MdmResponseBuf[index - 1] == '\r') {
            // Maximum response in numeric mode is 3 chars 'nnn\r'
            if (!alphaFlag) {
                modem_resp = atoi(MdmResponseBuf);
                //  LOG_PRINTF(("MdmResponseBuf %s \n ATOI of MdmResponseBuf %d",MdmResponseBuf,modem_resp));
                break;
            } else if (alphaFlag)
                LOG_PRINTF(("Command Response Buffer %s", MdmResponseBuf));
        } else if ((index != 0) && (MdmResponseBuf[index - 1] != '\r')) {
            //ERR_BEEP();
            //SVC_WAIT(300);
            //ERR_BEEP();
            //SVC_WAIT(300);
            //ERR_BEEP(); 
            if (MdmResponseBuf[index - 1] == '2')
                modem_resp = 0;


            // modem_resp=999;
            break;
        }

        if ((SVC_TICKS(0, (long *) &l_max_ticks)) == 0) {
            modem_resp = E_X_HR_TIMEOUT;
            break;
        }
    };
    LOG_PRINTF(("mdm Response %s", MdmResponseBuf));   

    return (modem_resp);
}



int my_xmdm_inInitModem(int h_modem,int i_max_wait,int a,int b,int c,int d,int e) {
    va_list p_args;
    int retVal = HAYES_OK ;
    char mdmEnvBuf[65] = {
        0
    } ;
    char envVarBuf[5] = {
        0
    } ;
    long l_max_ticks;
    int envVarValue = -1;
    int i;

    //  va_start(p_args,va_alist) ;
    // p_args = (va_list) &va_alist;
    
    //LeeChyi - 31082005: Commented Off - START
    if (fMDMInitDone != VS_FALSE)  // intended to Init modem only once.
        return retVal;
    //fMDMInitDone = VS_TRUE;
    //LeeChyi - END


    if (i_max_wait > 0)
        l_max_ticks = set_itimeout(-1, i_max_wait, TM_SECONDS);
    else
        return E_INVALID_PARM;      


    //  while ((( envVarValue = va_arg( p_args,int )) != -1 ) && (retVal == HAYES_OK ) && ( SVC_TICKS( 0, (long *)&l_max_ticks )))
    for (i = 1; i <= 5; ++i) {
        switch (i) {
        case 1:
            envVarValue = a;
            break;
        case 2:
            envVarValue = b;
            break;
        case 3:
            envVarValue = c;
            break;
        case 4:
            envVarValue = d;
            break;
        case 5:
            envVarValue = e;
            break;
        }
        if ((retVal != HAYES_OK) || (SVC_TICKS(0, (long *) &l_max_ticks) == 0)) {
            pdebug(("ERROR"));
            LOG_PRINTFF((0x08L, "ERROR of Hayes command"));

            break;
        }
        sprintf(envVarBuf, "M%d", envVarValue);
        memset(mdmEnvBuf, '\0', sizeof(mdmEnvBuf));
        LOG_PRINTFF((0x08L, "envVarBuf=%s", envVarBuf));        
        if ((get_env(envVarBuf, mdmEnvBuf, sizeof(mdmEnvBuf))) > 0) {
            LOG_PRINTFF((0x08L, "mdmEnvBuf=%s", mdmEnvBuf));    
            if ((retVal = Lenz_xhayes_send_cmd(h_modem, mdmEnvBuf)) == (strlen(mdmEnvBuf) + 3))
	     {
	         // Vinaya HS - The below code is commented and new code introduced so that both 3750 and 5150 will work.
	         //			    For 5150 we do not need the dreaded modem delay between commands.

		  #if 0
		  
                retVal = xhayes_response(h_modem, -1, 2);
		  
                if (retVal != 0)
                	LOG_PRINTFF((0x08L, "Modem Response for Config Entry %s : %d", mdmEnvBuf, retVal));

		  // LENZ SVC_WAIT (100); // Give some time delay between succesive commands

		 #endif /* 0 */

		 if ((retVal = inGetMdmResponse (h_modem, 2)) != HAYES_OK)
            	 {
               	pdebug (("inGetMdmResponse = %d", retVal));
            	 }
						 
		#ifndef __arm
		
			SVC_WAIT (MDM_CMD_WAIT_TIME); // Give Modem time to process command

		#endif
		 
            } else {
                LOG_PRINTFF((0x08L, "xhayes_send_cmd return value:  %d", retVal));
                retVal = E_WRITE;
            }
        } else
            LOG_PRINTFF((0x08L, "Config Entry %s Not Found", envVarBuf));
    }

    xmdm_flush(h_modem);
    return (retVal);
}


int Lenz_xhayes_send_cmd(int h_modem,const char* cmd_buff) {
    int retVal = -1 ;
    char cmdbuffer[70] = {
        0
    } ;
    memset(cmdbuffer, '\0', sizeof(cmdbuffer));
    sprintf(cmdbuffer, "AT%s\r", cmd_buff);
    return(write(h_modem, cmdbuffer, strlen(cmdbuffer)));
}

